package com.boyiis.sell.controller;

import com.boyiis.sell.enums.ResultEnum;
import com.boyiis.sell.exception.SellException;
import com.boyiis.sell.model.dto.OrderDTO;
import com.boyiis.sell.service.OrderService;
import com.boyiis.sell.service.PayService;
import com.lly835.bestpay.model.PayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayService payService;

    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String order, @RequestParam("returnUrl") String returnUrl) {

        //1.查询订单
        OrderDTO orderDTO = orderService.findOne(order);
        if (null == orderDTO) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }

        //2.发起支付
        PayResponse payResponse = payService.create(orderDTO);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("payResponse", payResponse);
        map.put("returnUrl", returnUrl);


        return new ModelAndView("/pay/create");
    }

    /**
     * 接收微信返回的支付结果
     * @param notifyData
     */
    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData) {
        payService.notify(notifyData);

        //返回给微信处理结果
        return new ModelAndView("pay/success");
    }
}
